package com.tensquare.test.qa.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceportor implements HandlerInterceptor {
   @Autowired
   private JwtUtil jwtUtil ;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("经过了拦截器");

        String header = request.getHeader("Authorization");
        if (header != null || !"".equals(header)) {
            if (header.startsWith("Bearer ")) {
                //得到令牌
                String token = header.substring(7);
                //对令牌做验证
                try {
                    Claims claims = jwtUtil.parseJWT(token);
                    String roles = (String) claims.get("roles");

                    if (roles != null &&roles.equals("admin")){
                        request.setAttribute("claims_admin",token);

                    }
                    if (roles != null &&roles.equals("user")){
                        request.setAttribute("claims_user",token);
                        System.out.println("参数传入request:"+request.getAttribute("claims_uesr"));

                    }
                }catch (Exception e){
                    throw new RuntimeException("token错误");
                }

            }
        }


    return true;
    }
}
